<template>
  <div class="com-container">
    <div class="com-map" ref="mapRef"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';
import mapJson from '/src/assets/js/china.json'; // 确保正确导入 mapJson
import dayjs from 'dayjs'; // 确保正确导入 dayjs

export default {
  data() {
    return {
      mapInstance: null,
      geoCoordMap: {},
      routeData: [],
      filteredRouteData: [],
      updateInterval: null,
      departure: '',
      destination: '',
      selectedDate: '' // 增加一个selectedDate变量以获取用户选择的日期
    };
  },
  async mounted() {
    await this.loadGeoCoordMap();
    this.initMap();
    await this.loadRouteData();
    this.startAutoUpdate();

    window.addEventListener('resize', this.handleResize);
    window.addEventListener('filter-change', this.handleFilterChange);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
    window.removeEventListener('filter-change', this.handleFilterChange);
    clearInterval(this.updateInterval);
  },
  methods: {
    async loadGeoCoordMap() {
      try {
        const response = await axios.get('http://localhost:8000/flights/geoCoordMap');
        this.geoCoordMap = response.data;
        console.log('城市坐标数据加载成功:', this.geoCoordMap);
      } catch (error) {
        console.error('加载城市坐标数据失败:', error);
      }
    },
    async loadRouteData() {
      try {
        const response = await axios.get('http://localhost:8000/flights/routes');
        this.routeData = response.data.routes;
        this.applyFilter();
        console.log('航线数据加载成功:', this.routeData);
      } catch (error) {
        console.error('加载航线数据失败:', error);
      }
    },
    initMap() {
      if (this.$refs.mapRef) {
        echarts.registerMap('china', mapJson);
        this.mapInstance = echarts.init(this.$refs.mapRef);

        const series = this.createSeries();

        const option = {
          backgroundColor: '#000',
          title: {
            text: '模拟航线',
            subtext: '数据纯属虚构',
            left: 'center',
            textStyle: {
              color: '#fff'
            }
          },
          tooltip: {
            trigger: 'item',
            formatter: function (params) {
              if (params.seriesType === "effectScatter") {
                return `线路：${params.data.name} ${params.data.value[2]}`;
              } else if (params.seriesType === "lines") {
                return `${params.data.fromName} > ${params.data.toName}<br />${params.data.value}`;
              } else {
                return params.name;
              }
            }
          },
          legend: {
            orient: 'vertical',
            top: 'bottom',
            left: 'right',
            data: ['航线'],
            textStyle: {
              color: '#fff'
            },
            selectedMode: 'multiple'
          },
          geo: {
            map: 'china',
            label: {
              emphasis: {
                show: true,
                color: '#fff'
              }
            },
            roam: true,
            itemStyle: {
              normal: {
                areaColor: '#00186E',
                borderColor: '#195BB9',
                borderWidth: 1,
              },
              emphasis: {
                areaColor: '#2B91B7'
              }
            }
          },
          series: series
        };

        this.mapInstance.setOption(option);
      } else {
        console.error('mapRef 未正确引用');
      }
    },
    createSeries() {
      const planePath = 'path://M1705.06,1318.313v-89.254l-319.9-221.799l0.073-208.063c0.521-84.662-26.629-121.796-63.961-121.491c-37.332-0.305-64.482,36.829-63.961,121.491l0.073,208.063l-319.9,221.799v89.254l330.343-157.288l12.238,241.308l-134.449,92.931l0.531,42.034l175.125-42.917l175.125,42.917l0.531-42.034l-134.449-92.931l12.238-241.308L1705.06,1318.313z';

      const color = ['#a6c84c', '#ffa022', '#46bee9']; // 航线的颜色

      const convertData = (data) => {
        const res = [];
        for (let i = 0; i < data.length; i++) {
          const dataItem = data[i];
          const fromCoord = this.geoCoordMap[dataItem[0].name];
          const toCoord = this.geoCoordMap[dataItem[1].name];
          if (fromCoord && toCoord) {
            res.push({
              fromName: dataItem[0].name,
              toName: dataItem[1].name,
              coords: [fromCoord, toCoord],
              value: dataItem[1].value
            });
          }
        }
        return res;
      };

      const series = [
        {
          name: 'Top3 航线',
          type: 'lines',
          zlevel: 2,
          symbol: ['none', 'arrow'],
          symbolSize: 10,
          effect: {
            show: true,
            period: 6,
            trailLength: 0,
            symbol: planePath,
            symbolSize: 15
          },
          lineStyle: {
            normal: {
              color: color[0],
              width: 1,
              opacity: 0.6,
              curveness: 0.2
            }
          },
          data: convertData(this.filteredRouteData)
        },
        {
          name: 'Top3 航线',
          type: 'effectScatter',
          coordinateSystem: 'geo',
          zlevel: 2,
          rippleEffect: {
            brushType: 'stroke'
          },
          label: {
            normal: {
              show: true,
              position: 'right',
              formatter: '{b}'
            }
          },
          symbolSize: (val) => {
            const size = val[2] / 8;
            const maxSize = 5; // 设置最大图标大小
            return size > maxSize ? maxSize : size;
          },
          itemStyle: {
            normal: {
              color: color[0],
            },
            emphasis: {
              areaColor: '#2B91B7'
            }
          },
          data: this.filteredRouteData.map((dataItem) => ({
            name: dataItem[1].name,
            value: this.geoCoordMap[dataItem[1].name].concat([dataItem[1].value])
          }))
        }
      ];

      return series;
    },
    updateMap() {
      const series = this.createSeries();
      this.mapInstance.setOption({
        series: series
      });
    },
    startAutoUpdate() {
      this.updateInterval = setInterval(async () => {
        await this.loadRouteData();
      }, 5000); // 每5秒更新一次数据
    },
    handleResize() {
      if (this.mapInstance) {
        this.mapInstance.resize();
      }
    },
    applyFilter() {
      this.filterRoutes();
    },
    filterRoutes() {
      this.filteredRouteData = this.routeData.filter(route => {
        const routeDate = dayjs(route[0].time).format('YYYY-MM-DD');
        const selectedDate = dayjs(this.selectedDate).format('YYYY-MM-DD');

        const isDepartureMatch = this.departure ? route[0].name === this.departure : true;
        const isDestinationMatch = this.destination ? route[1].name === this.destination : true;
        const isDateMatch = this.selectedDate ? routeDate === selectedDate : true;

        return isDepartureMatch && isDestinationMatch && isDateMatch;
      });

      this.updateMap();
    }
,
    handleFilterChange(event) {
      this.departure = event.detail.startPosition;
      this.destination = event.detail.aimPosition;
      this.selectedDate = event.detail.selectedDate;
      this.applyFilter();

    }
  }
};
</script>

<style>
.com-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.com-map {
  width: 100%;
  height: 100%;
}
</style>
